<template>
  <!-- 标题 -->
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">信息管理</span>
    <el-button type="primary" style="float:right;margin-top:13px;" @click="beforeAddCoupon">+ 新建优惠券</el-button>
  </div>
  <!-- 查询表单 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true" :model="searchForm" class="search-form" label-position="right">
      <el-form-item label="优惠券名称" style="width:320px;">
        <el-input
            v-model="searchForm.couponName"
            placeholder="请输入优惠券名称"
            clearable
        /></el-form-item>
      <el-form-item label="优惠券类型" style="width:320px;">
        <el-select
            v-model="searchForm.couponType"
            placeholder="全部"
            clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="满减" value="满减"></el-option>
          <el-option label="折扣" value="折扣"></el-option>
          <el-option label="随机" value="随机"></el-option>
          <!-- 可扩展更多类型，或通过接口动态加载 -->
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券状态" style="width:320px;">
        <el-select
            v-model="searchForm.status"
            placeholder="全部"
            clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="未开始" value="未开始"></el-option>
          <el-option label="进行中" value="进行中"></el-option>
          <el-option label="已结束" value="已结束"></el-option>
          <!-- 可扩展更多状态，或通过接口动态加载 -->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 优惠券列表 -->
  <el-card style="margin:20px;">
    <el-table
        :data="tableData"
        stripe
        class="coupon-table"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="编号" width="80"></el-table-column>
      <el-table-column prop="couponName" label="优惠券名称"></el-table-column>
      <el-table-column prop="applicable" label="适用范围"></el-table-column>
      <el-table-column prop="couponType" label="优惠类型"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === '进行中' ? 'success' : ''">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="usageNum" label="数量"></el-table-column>
      <el-table-column prop="maxUsageLimit" label="单次消费限制张数"></el-table-column>
      <el-table-column prop="enableStatus" label="启用状态">
        <template #default="scope">
          <el-switch
              v-model="scope.row.enableStatus"
              @change="handleEnableChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)" style="color: #f56c6c;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 20px;"
        />
      </div></template>
  </el-card>
  <el-dialog title="内容信息" v-model="addCouponDialogVisible" width="600px">
    <!-- 优惠券发布表单 -->
    <el-form
        ref="couponForm"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="coupon-form"
    >
      <!-- 优惠券类型 -->
      <el-form-item label="优惠券类型" prop="couponType">
        <el-select v-model="form.couponType" placeholder="请选择优惠券类型">
          <el-option label="满减" value="满减"></el-option>
          <el-option label="折扣" value="折扣"></el-option>
          <el-option label="随机" value="随机"></el-option>
        </el-select>
      </el-form-item>

      <!-- 优惠券名称 -->
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input
            v-model="form.couponName"
            placeholder="最多10个字"
            max-length="10"
            show-word-limit
        />
      </el-form-item>

      <!-- 优惠券描述 -->
      <el-form-item label="优惠券描述" prop="couponDesc">
        <el-input
            v-model="form.couponDesc"
            type="textarea"
            placeholder="最多10个字"
            max-length="10"
            show-word-limit
        />
      </el-form-item>

      <!-- 发行总量 -->
      <el-form-item label="发行总量" prop="totalCount">
        <el-input
            v-model.number="form.totalCount"
            placeholder="不能超过100万张"
            max="1000000"
            show-word-limit
        />
      </el-form-item>

      <!-- 适用范围 -->
      <el-form-item label="适用范围">
        <el-radio-group v-model="form.scopeType">
          <el-radio label="全场通用">全场通用</el-radio>
          <el-radio label="指定类型">指定类型</el-radio>
          <el-radio label="指定商品">指定商品</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 优惠券面额 -->
      <el-form-item label="优惠券面额" prop="denomination">
        <el-input
            v-model.number="form.denomination"
            placeholder="请输入面额"
        />
        <span style="margin-left: 5px;">¥</span>
      </el-form-item>

      <!-- 有效期 -->
      <el-form-item label="有效期">
        <el-radio-group v-model="form.validityType">
          <el-radio label="指定时间段">指定时间段</el-radio>
          <el-radio label="领取后有效">从领取日期起多少天内有效</el-radio>
        </el-radio-group>

        <div style="margin-top: 10px;" v-if="form.validityType === '指定时间段'">
          <el-date-picker
              v-model="form.startTime"
              type="date"
              placeholder="开始日期"
              style="margin-right: 10px;"
          />
          <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="结束日期"
          />
        </div>

        <div style="margin-top: 10px;" v-else>
          <el-input
              v-model.number="form.validityDays"
              placeholder="请输入有效天数"
              style="width: 200px; margin-right: 10px;"
          />
          天内有效
        </div>
      </el-form-item>

      <!-- 每人限额 -->
      <el-form-item label="每人限额" prop="limitPerPerson">
        <el-input
            v-model.number="form.limitPerPerson"
            placeholder="默认每人限领一张"
        />
        张
      </el-form-item>

      <!-- 互斥规则 -->
      <el-form-item label="互斥规则">
        <el-radio-group v-model="form.exclusionRule">
          <el-radio label="不互斥">不互斥</el-radio>
          <el-radio label="与指定类型互斥">与指定类型互斥</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 消费门槛 -->
      <el-form-item label="消费门槛">
        <el-radio-group v-model="form.consumptionThreshold">
          <el-radio label="无门槛">无门槛</el-radio>
          <el-radio label="订单满">订单满</el-radio>
        </el-radio-group>

        <el-input
            v-model.number="form.orderAmount"
            placeholder="请输入订单满减金额"
            style="width: 200px; margin-top: 10px; margin-left: 10px;"
            v-if="form.consumptionThreshold === '订单满'"
        />
        元
      </el-form-item>

      <!-- 叠加规则 -->
      <el-form-item label="叠加规则" prop="stackRule">
        <el-input
            v-model.number="form.stackRule"
            placeholder="默认每人最多使用一张"
        />
        张
      </el-form-item>

      <!-- 最大抵扣面额 -->
      <el-form-item label="最大抵扣面额" prop="maxDeduction">
        <el-input
            v-model.number="form.maxDeduction"
            placeholder="最大抵扣面额"
        />
        元
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">发布</el-button>
        <el-button @click="handleReset1">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox, ElTag, ElSwitch, ElTable, ElTableColumn, ElPagination, ElBreadcrumb, ElBreadcrumbItem, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus';
import axios from 'axios';
import { onMounted } from 'vue';

onMounted(() => {
  handleQuery();
});


// 接口基础地址（后端运行在 localhost:5050）
const BASE_URL = 'http://localhost:5050';
// 搜索表单数据
const searchForm = reactive({
  couponName: '',
  couponType: '',
  status: '',
});
//定义变量保存分页器的当前页数
const currentPage = ref(1);
//定义变量保存分页器的每页显示多少条
const pageSize = ref(5);
// 查询优惠券列表
const handleQuery = () => {
    console.log(searchForm.value);
    searchForm.pageSize = pageSize.value;
    searchForm.page = currentPage.value;

    axios.get(BASE_URL+'/admin/marketing/coupon/info/list?'+ searchForm.value)
        .then((response)=>{
          console.log('响应数据:', response.data);

          if(response.data.code==0){
            tableData.value = response.data.data.objects;
            total.value = response.data.data.total;
            console.log('tableData:', response.data.data.objects);
          }else{
            ElMessage.error(response.data.message);
          }
        })
        .catch((error)=>{
          console.error('请求错误:', error);
          ElMessage.error('请求失败: ' + error.message);
        });
  }
// 重置查询条件
const handleReset = () => {
  searchForm.couponName = '';
  searchForm.couponType = '';
  searchForm.status = '';
  handleQuery();
};

// 每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleQuery();
};

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleQuery();
};

// 编辑优惠券
const handleEdit = (row) => {
  // 跳转到编辑页面，携带优惠券 ID
  console.log('编辑优惠券：', row);
  // 示例：router.push(`/coupon/edit/${row.id}`);
};

// 新建优惠券
const handleCreate = () => {
  // 跳转到新建页面
  console.log('新建优惠券');
  // 示例：router.push('/coupon/create');
};
const handleDelete = () => {
  // 跳转到新建页面
  console.log('删除优惠券');
  // 示例：router.push('/coupon/create');
};
const handleEnableChange = () => {
  // 跳转到新建页面
  console.log('更新优惠券');
  // 示例：router.push('/coupon/create');
};

// 删除优惠券
// const handleDelete = (row) => {
//   ElMessageBox.confirm(
//       '此操作将永久删除该优惠券, 是否继续?',
//       '提示',
//       {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//   ).then(() => {
//     axios.delete(BASE_URL+'/admin/marketing/coupon/info/delete/${row.id}').then((response) => {
//       if (response.data.code == 0) {
//         ElMessage.success('删除成功!');
//         handleQuery(); // 重新查询列表
//       } else {
//         ElMessage.error(response.data.msg || '删除失败');
//       }
//     }).catch(err => {
//       console.error(err);
//       ElMessage.error('删除接口异常');
//     });
//   }).catch(() => {
//     ElMessage.info('已取消删除');
//   });
//  };

// 启用状态改变
// const handleEnableChange = (row) => {
//   // 调用更新状态接口
//   const param = {
//     id: row.id,
//     enableStatus: row.enableStatus
//   };
//
//   axios.post(BASE_URL+'/admin/marketing/coupon/info/updateEnable', param).then((response)=> {
//     if (response.data.code == 0) {
//       ElMessage.success('状态更新成功');
//     } else {
//       ElMessage.error(response.data.msg || '状态更新失败');
//       // 回滚开关状态
//       row.enableStatus = !row.enableStatus;
//     }
//   }).catch(err => {
//     console.error(err);
//     ElMessage.error('状态更新接口异常');
//     // 回滚开关状态
//     row.enableStatus = !row.enableStatus;
//   });
// };



// 表单数据
const form = reactive({
  couponType: '', // 优惠券类型
  couponName: '', // 优惠券名称
  couponDesc: '', // 优惠券描述
  totalCount: 0, // 发行总量
  scopeType: '全场通用', // 适用范围
  denomination: 0, // 优惠券面额
  validityType: '指定时间段', // 有效期类型
  startTime: null, // 开始日期（指定时间段）
  endTime: null, // 结束日期（指定时间段）
  validityDays: 0, // 有效天数（领取后有效）
  limitPerPerson: 1, // 每人限额
  exclusionRule: '不互斥', // 互斥规则
  consumptionThreshold: '无门槛', // 消费门槛
  orderAmount: 0, // 订单满减金额
  stackRule: 1, // 叠加规则
  maxDeduction: 0 // 最大抵扣面额
});

// 表单校验规则
const rules = {
  couponType: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  couponName: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { max: 10, message: '最多10个字', trigger: 'blur' }
  ],
  couponDesc: [
    { required: true, message: '请输入优惠券描述', trigger: 'blur' },
    { max: 10, message: '最多10个字', trigger: 'blur' }
  ],
  totalCount: [
    { required: true, message: '请输入发行总量', trigger: 'blur' },
  ],
  denomination: [
    { required: true, message: '请输入优惠券面额', trigger: 'blur' }
  ],
  limitPerPerson: [
    { required: true, message: '请输入每人限额', trigger: 'blur' }
  ],
  stackRule: [
    { required: true, message: '请输入叠加规则', trigger: 'blur' }
  ],
  maxDeduction: [
    { required: true, message: '请输入最大抵扣面额', trigger: 'blur' }
  ]
};

// 提交表单
const handleSubmit = () => {
  let data = qs.stringify(form.value);
  // 调用后端接口发布优惠券
  axios.post(BASE_URL+'/admin/marketing/coupon/info/save', form).then((response) => {
    if (response.data.code ==0) { // 假设后端返回 Result 格式，code=200 为成功
      ElMessage.success('发布成功！');
      handleReset1(); // 重置表单
    } else {
      ElMessage.error(response.data.msg || '发布失败');
    }
  })
};

// 重置表单
const handleReset1 = () => {
  // @ts-ignore
  couponForm.value.resetFields();
  // 重置自定义字段
  form.scopeType = '全场通用';
  form.validityType = '指定时间段';
  form.startTime = null;
  form.endTime = null;
  form.validityDays = 0;
  form.consumptionThreshold = '无门槛';
  form.orderAmount = 0;
};

const addCouponDialogVisible=ref( false)
const beforeAddCoupon = () => {
  addCouponDialogVisible.value = true
}

// 表格数据、分页相关
const tableData = ref([]);
const total = ref();
const couponForm = ref(null);




// 初始化加载列表
handleQuery();

</script>

<style scoped>
.pagination{
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.coupon-table {
  margin-bottom: 20px;
}
</style>